#include <iostream>

#include "citizen.hpp"
#include "barter_market.hpp"

namespace {
bool offers_tradeable(const barter_market::offer& a, const barter_market::offer& b) {
	return a.offered == b.wanted && a.wanted == b.offered &&
	       a.quantity_offered >= b.quantity_wanted &&
		   a.quantity_wanted <= b.quantity_offered;
}

void make_trade(barter_market::offer& a, barter_market::offer& b) {
	//get the items we're buying
	a.trader->get_item(b.offered->id(), b.quantity_offered);
	b.trader->get_item(a.offered->id(), a.quantity_offered);

	//lose the items we offered
	a.trader->get_item(a.offered->id(), -a.quantity_offered);
	b.trader->get_item(b.offered->id(), -b.quantity_offered);
}
}

void barter_market::add_offer(const offer& o)
{
	offers_.push_back(o);
}

void barter_market::resolve_market()
{
	while(!offers_.empty()) {
		for(std::vector<offer>::iterator i = offers_.begin(); i < offers_.end()-1; ++i) {
			if(offers_tradeable(offers_.back(), *i)) {
				make_trade(*i, offers_.back());
				offers_.erase(i);
				break;
			}
		}

		offers_.pop_back();
	}
}
